package TableAdditions;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import Tables.CustomerTableInterface;
import Tables.PersonelTableInterface;

public class PersonelAddition extends JFrame {
	
    private JTextField personelNameField;
    private JTextField personelPhoneField;
    private JTextField addressField;
    private JComboBox vehicleNameCombo;
    
    int[] personelId;
    int[] vehicleId;
    int driverId2=0;
    
	public String personelName;
	public String address;
	public String personelPhone;
	public String jobName;
	public String vehicleName;
	public static boolean driverDuplicateFlag=true;
	
	
    private JButton customerAddButton;
    PersonelTableInterface cti;
    public PersonelAddition(final PersonelTableInterface cti) {
		super("Personel Ekleme Ekranı");
		this.cti = cti;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(600,200);
		getContentPane().setLayout(null);
		
		JLabel codeLabel = new JLabel("Personel Adı");
		codeLabel.setBounds(20, 10, 90, 20);
		getContentPane().add(codeLabel);
		
		personelNameField = new JTextField();
		personelNameField.setBounds(124, 11, 115, 20);
		getContentPane().add(personelNameField);
		personelNameField.setColumns(10);
		
		JLabel authorityLabel = new JLabel("Telefon");
		authorityLabel.setBounds(20, 40, 90, 20);
		getContentPane().add(authorityLabel);
		
		personelPhoneField = new JTextField();
		personelPhoneField.setBounds(124, 43, 115, 20);
		getContentPane().add(personelPhoneField);
		personelPhoneField.setColumns(10);
		
		JLabel nameLabel = new JLabel("Adres");
		nameLabel.setBounds(270, 10, 90, 20);
		getContentPane().add(nameLabel);
		
		addressField = new JTextField();
		addressField.setBounds(370, 10, 115, 20);
		getContentPane().add(addressField);
		addressField.setColumns(10);
		
		
		vehicleNameCombo = new JComboBox();
		vehicleNameCombo.setBounds(370, 40, 115, 20);
		getContentPane().add(vehicleNameCombo);
		   try {
			   Connection conn = null;
		        Statement stmt = null;
		        ResultSet rss = null;

		        String url = "jdbc:mysql://localhost:3306/mydb";
		        String user = "root";
		        String password = "qweasdzxc";
		        
		        conn = (Connection) DriverManager.getConnection(url, user, password);
				stmt = (Statement) conn.createStatement();
				


					
					
					
					vehicleNameCombo.addItem("Araç Plaka");
					rss=stmt.executeQuery("SELECT * from vehicle WHERE activity='1'");
					
					int counter2=0;
					while(rss.next()){
						counter2++;
						
					}
					if(counter2!=0){
						rss.first();
					vehicleId= new int[counter2];
					int m=0;
					if(rss.getInt("vehicle_availability")>0)
					{
					vehicleNameCombo.addItem(rss.getString("vehicle_licence_plate"));
					vehicleId[m]=rss.getInt("vehicle_id");
					m++;
					}
				
					
				
					while(rss.next()){
						if(rss.getInt("vehicle_availability")>0)
						{
						vehicleId[m]=rss.getInt("vehicle_id");
						vehicleNameCombo.addItem(rss.getString("vehicle_licence_plate"));
						m++;
						}
					}
					}
				
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		JLabel address1Label = new JLabel("Araç");
		address1Label.setBounds(270, 40, 90, 20);
		getContentPane().add(address1Label);
		
	
		
		
		customerAddButton = new JButton("Ekle");
		customerAddButton.setForeground(Color.BLACK);
		customerAddButton.setFont(new Font("Arial", Font.BOLD, 16));
		customerAddButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
			    
				
				
				personelName=personelNameField.getText();
				address=addressField.getText();
				personelPhone=personelPhoneField.getText();	
				vehicleName=(String) vehicleNameCombo.getSelectedItem();
				int vNum=-1;
	
				
				
				System.out.println("Ready to execute sql");
				 	Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";

			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            //st.executeUpdate("INSERT INTO job " + "VALUES (1, 'deneme')");
			         //   st.executeUpdate("UPDATE customer SET customer_phone='0554755' WHERE customer_name='rehber';");
			           
			            int i=0;
			            if(!vehicleName.equals("Araç Plaka")){
			            rs=st.executeQuery("SELECT vehicle_id from vehicle WHERE vehicle_licence_plate='"+vehicleName+"' and activity='1'");
			            while(rs.next())
			            {
			            	i++;
			            	vNum=rs.getInt("vehicle_id");
			            }
			            }else{
			            	vNum=-1;
			            }
			            
			            
			            rs=st.executeQuery("SELECT * FROM personel WHERE activity=1");
			            driverDuplicateFlag=true;
						while(rs.next()){
							if(rs.getString("personel_name").equals(personelName)){
								driverDuplicateFlag=false;
							}
						}
						
								
						String insert="INSERT INTO personel (personel_name,personel_phone,personel_address,personel_vehicle_id)";
						String values="VALUES ('"+personelName+"'" +
						",'"+personelPhone+"','"+address+"','"+vNum+"')";
						int messageType = JOptionPane.PLAIN_MESSAGE;
						
						if(driverDuplicateFlag==true){
							st.executeUpdate(insert + values);
							
							rs=st.executeQuery("SELECT * from personel");
							int driverId=-1;
							while(rs.next()){
								if(personelName.equals(rs.getString("personel_name")) && personelPhone.equals(rs.getString("personel_phone"))
										&& address.equals(rs.getString("personel_address"))){
									driverId=rs.getInt("personel_id");
								}
							}
							
							st.executeUpdate("UPDATE vehicle SET vehicle_availability=0,vehicle_driver_id='"+driverId+"' where vehicle_id='"+vNum+"'");
							JOptionPane.showMessageDialog(null, "Kayıt Alınmıştır", "Uyarı!!", messageType);
						}else{
							 JOptionPane.showMessageDialog(null, "Personel adı sistemde kayıtlı.", "Hata!!", messageType);
						}
			            //addTa(newRow[0]);
			            //st.executeUpdate("DELETE FROM job");
			       
						
						
			          
			           
			            con.close();
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
			        
			        // this will make sure WindowListener.windowClosing() et al. will be called.
			      //  WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
			        //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);

			        // this will hide and dispose the frame, so that the application quits by
			        // itself if there is nothing else around. 
			        cti.addNewItem();
			        setVisible(false);
			        dispose();
			}});
		
		customerAddButton.setBounds(385, 102, 100, 30);
		getContentPane().add(customerAddButton);
		
		
	setVisible(true);  
		
	}
  
   /* public static void main(String[] args) {
		new PersonelAddition();
	}*/

}
